<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="table"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :tableColumn="tableColumn"
        requestName="getListHandle"
        :tableData="tableData"
        @add="operateHandle($event, 'add')"
        @delete="operateHandle($event, 'delete')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @rowDelete="operateHandle($event, 'rowDelete')"
        @dictConfiguration="operateHandle($event, 'dictConfiguration')"
      />
    </div>

    <TrEditPopup
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      @close="isShowEdit = false"
      @confrim="dictConfirmHandle"
    />

    <TrLayout
      v-model="isShowPopup"
      :title="dictTitle"
      :isNeedFooter="false"
      :width="1227"
      @close="closeDictPopupHandle"
    >
      <TrSearch
        ref="dictSearch"
        paddingStyle="0 0 24px 0"
        :searchShowList="dictSearchShowList"
        :isDeepSearch="true"
        v-model="dictSearchParams"
        @search-back="searchDictHandle"
        @reset-back="resetDictParamsHandle"
        v-if="searchShowList.length > 0"
      />

      <TrTable
        lazy
        isNeedSelection
        isPopup
        isNeedLine
        ref="dictTable"
        :loadFun="loadFun"
        :btnList="dictBtnList"
        :tableColumn="dictTableColumn"
        :tableData="dictTableData"
        :isNeedPagination="false"
        @dictAdd="operateHandle($event, 'dictAdd')"
        @dictDelete="operateHandle($event, 'dictDelete')"
        @dictAddChild="operateHandle($event, 'dictAddChild')"
        @dictRowDelete="operateHandle($event, 'dictRowDelete')"
        @dictRowEdit="operateHandle($event, 'dictRowEdit')"
      />

      <TrEditPopup
        v-model="isShowDictEdit"
        :title="checkTitle"
        :valueObj.sync="dictFormObj"
        :formData="dictFormData"
        :list="dictPopupList"
        @close="isShowDictEdit = false"
        @confrim="dictPopupConfirmHandle"
      />
    </TrLayout>
  </div>
</template>

<script>
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import TrSearch from "@/components/Tr-search/Tr-search.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";

import {
  getDictBizList,
  getDictChildList,
  addDict,
  removeDict,
  updateDict,
  getDictTree,
  // getDictionary,
} from "@/api/system/dict";

export default {
  name: "DictBox",
  components: {
    TrTable,
    TrLayout,
    TrSearch,
    TrEditPopup,
  },
  data() {
    return {
      // 列表
      tableData: [],
      selectList: [],
      commonTableColumns: [
        { type: "text", label: "字典编号", value: "code" },
        { type: "text", label: "字典名称", value: "dictValue" },
        { type: "text", label: "封存", value: "sealedText" },
      ],
      searchShowList: [
        {
          id: "code",
          type: "input",
          width: 30,
          label: "字典编号",
          value: "",
        },
        {
          id: "dictValue",
          type: "input",
          width: 30,
          label: "字典名称",
          value: "",
        },
      ],
      searchParams: {
        current: 1,
        size: 10,
      },
      totalNum: 0,
      btnList: [
        {
          label: "新增",
          option: "add",
          color: "blue",
        },
        {
          label: "删除",
          option: "delete",
          color: "white",
          isRelaTable: true,
        },
      ],

      // 新增编辑弹窗
      formObj: {},
      formData: {},
      popupList: [],
      isShowEdit: false,
      currentHandle: "",

      // 字典配置弹窗
      isShowPopup: false,
      dictTitle: "字典配置",
      dictTableData: [],
      dictBtnList: [
        {
          label: "新增",
          option: "dictAdd",
          color: "blue",
        },
        {
          label: "删除",
          option: "dictDelete",
          color: "white",
          isRelaTable: true,
        },
      ],
      dictSearchParams: {},
      dictSearchShowList: [
        {
          id: "code",
          type: "input",
          width: 30,
          label: "字典编号",
          value: "",
        },
        {
          id: "dictValue",
          type: "input",
          width: 30,
          label: "字典名称",
          value: "",
        },
      ],

      // 字典配置内新增编辑弹窗
      dictFormObj: {},
      dictFormData: {},
      dictPopupList: [],
      isShowDictEdit: false,
      currentDictValue: {},
      currentRowValue: {},
    };
  },
  mounted() {
    // getDictionary({ code: "testAgain" }).then((res) => {
    //   console.log(res);
    // });
    // 初始化popupList
    this.popupList = this.getPopupList();
    // 初始化dictPopupList
    this.dictPopupList = this.getPopupList(true);
    // this.getListHandle(this.searchParams);
  },

  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        dictAdd: "新增",
        dictAddChild: "新增子项",
        default: "编辑",
      };
      return titles[this.currentHandle] || titles.default;
    },

    tableColumn() {
      return [
        ...this.commonTableColumns,
        {
          type: "option",
          label: "操作",
          width: 120,
          showBtnList: [
            { label: "编辑", option: "rowEdit" },
            { label: "删除", option: "rowDelete" },
            { label: "字典配置", option: "dictConfiguration" },
          ],
        },
      ];
    },

    dictTableColumn() {
      const baseColumns = this.commonTableColumns;
      const dictKeyColumn = {
        type: "text",
        label: "字典键值",
        value: "dictKey",
      };
      const operationColumn = {
        type: "option",
        label: "操作",
        showBtnList: [
          { label: "编辑", option: "dictRowEdit" },
          { label: "删除", option: "dictRowDelete" },
          { label: "新增子项", option: "dictAddChild" },
        ],
      };

      return [
        ...baseColumns.filter(
          (col) => col.value === "code" || col.value === "dictValue"
        ),
        dictKeyColumn,
        ...baseColumns.filter(
          (col) => col.value !== "code" && col.value !== "dictValue"
        ),
        operationColumn,
      ];
    },
    ids() {
      let ids = [];
      this.$refs.table.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    dictIds() {
      let ids = [];
      this.$refs.dictTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    getPopupList(isDictPopup = false) {
      const commonFields = [
        {
          label: "字典编号",
          type: "input",
          width: 50,
          value: "",
          id: "code",
          disabled: isDictPopup,
        },
        {
          label: "字典名称",
          type: "input",
          width: 50,
          value: "",
          id: "dictValue",
        },
        {
          label: "字典排序",
          type: "input",
          width: 50,
          value: "",
          id: "sort",
        },
        {
          label: "封存",
          type: "radio",
          width: 50,
          value: 0,
          id: "isSealed",
          list: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
        },
        {
          isNeed: false,
          label: "字典备注",
          type: "textarea",
          width: 100,
          value: "",
          id: "remark",
        },
      ];

      if (isDictPopup) {
        return [
          ...commonFields.slice(0, 2),
          {
            label: "上级字典",
            type: "select",
            width: 50,
            value: "",
            id: "parentId",
            list: [],
            disabled: true,
            isNeed: false,
          },
          {
            label: "字典键值",
            type: "input",
            width: 50,
            value: "",
            id: "dictKey",
          },
          ...commonFields.slice(2),
        ];
      }

      return commonFields;
    },

    operateHandle(val, type) {
      this.currentHandle = type;
      this.currentRowValue = "";
      this.formData = {};
      this.dictFormData = {};
      const actions = {
        add: () => {
          // const maxSort = Math.max(
          //   ...this.tableData.map((item) => item.sort || 0),
          //   0
          // );
          this.formData = { sort: this.totalNum + 1, isSealed: 0 };
          this.isShowEdit = true;
        },
        delete: () => {
          this.deleteDictHandle({ id: this.ids });
        },
        dictConfiguration: () => {
          this.currentDictValue = val;
          this.isShowPopup = true;
          this.loadDictChildList();
        },
        dictAdd: async () => {
          await this.openDictAddHandle();
          this.isShowDictEdit = true;
        },
        dictDelete: () => {
          this.deleteDictHandle({ id: this.dictIds });
        },
        rowEdit: () => {
          this.currentDictValue = val;
          this.formData = { ...val };
          this.isShowEdit = true;
        },
        rowDelete: () => this.deleteDictHandle(val),
        dictAddChild: async () => {
          this.currentRowValue = val;
          await this.openDictAddHandle(val);
          this.isShowDictEdit = true;
        },
        dictRowDelete: () => this.deleteDictHandle(val),
        dictRowEdit: async () => {
          delete val.children;
          this.currentRowValue = val;
          this.dictFormData = { ...val };
          await this.openDictAddHandle(val);
          this.isShowDictEdit = true;
        },
      };

      const action = actions[type];
      if (action) action();
    },

    async getListHandle() {
      try {
        const { data } = await getDictBizList(this.searchParams);
        if (data.code !== 200) return;
        this.$validateData(data.data);
        this.totalNum = data.data.total;
        this.tableData = data.data.records.map(this.formatTableItem);
        this.tableData.sort((a, b) => a.sort - b.sort);
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("获取列表失败");
      }
    },

    formatTableItem(item) {
      return {
        ...item,
        sealedText: item.isSealed === 0 ? "否" : "是",
      };
    },

    async loadDictChildList() {
      try {
        const res = await getDictChildList({
          ...this.dictSearchParams,
          parentId: this.currentDictValue.id,
        });
        if (res.data.code === 200) {
          const setSealedText = (item) => {
            item.sealedText = item.isSealed === 0 ? "否" : "是";
            if (item.children) {
              item.children.sort((child) => child.sort);
              item.children.forEach(setSealedText);
            }
          };

          res.data.data.forEach(setSealedText);
          res.data.data.sort((item) => item.sort);
          this.dictTableData = res.data.data;
        }
      } catch (error) {
        console.error("加载字典子列表失败:", error);
      }
    },

    loadFun(tree, treeNode, resolve) {
      getDictChildList(this.currentDictValue.id).then((res) => {
        res.data.data.forEach(
          (item) => (item.sealedText = item.isSealed === 0 ? "否" : "是")
        );

        resolve(res.data.data);
      });
    },

    async openDictAddHandle(val) {
      const parentId = val ? val.parentId : this.currentDictValue.parentId;
      try {
        const { data } = await getDictTree();
        const mapData = this.findAndMapChildren(data.data, parentId) || [];

        this.dictPopupList = this.dictPopupList.map((item) => {
          if (item.id === "parentId") {
            if (this.currentHandle === "dictRowEdit") {
              this.dictFormData.parentId = parentId;
            }
            return { ...item, list: mapData, value: parentId };
          }
          if (item.id === "code") {
            return { ...item, value: this.currentDictValue.code };
          }
          if (item.id === "sort") {
            const maxSort = Math.max(
              ...this.dictTableData.map((item) => item.sort || 0),
              0
            );
            return { ...item, value: maxSort + 1 };
          }
          return item;
        });
      } catch (error) {
        console.error("获取字典树失败:", error);
        this.$message.error("获取字典树失败");
      }
    },

    findAndMapChildren(items, targetId) {
      for (const item of items) {
        if (item.id === targetId) {
          return [{ label: item.title, value: item.id }].concat(
            item.children?.map((child) => ({
              label: child.title,
              value: child.id,
            })) || []
          );
        }
        if (item.hasChildren && item.children) {
          const result = this.findAndMapChildren(item.children, targetId);
          if (result) return result;
        }
      }
      return null;
    },

    async dictPopupConfirmHandle() {
      const parentId =
        this.currentHandle === "dictAddChild" ||
        this.currentHandle === "dictRowEdit"
          ? this.currentRowValue.id
          : this.currentDictValue.id;
      console.log("this.currentHandle", this.currentHandle);
      try {
        if (this.currentHandle === "dictRowEdit") {
          delete this.dictFormObj.parentId;
          await updateDict(
            Object.assign(this.currentRowValue, this.dictFormObj)
          );
        } else {
          await addDict({
            ...this.dictFormObj,
            parentId,
          });
        }

        this.$message.success(this.$t("msg.success"));
        this.loadDictChildList();
        this.isShowDictEdit = false;
      } catch (error) {
        console.error("添加字典子项失败:", error);
      }
    },

    closeDictPopupHandle() {
      this.dictSearchParams = {};
      this.dictTableData = [];
      this.isShowPopup = false;
    },

    async dictConfirmHandle() {
      try {
        if (this.currentHandle === "rowEdit") {
          await updateDict(Object.assign(this.currentDictValue, this.formObj));
        } else {
          await addDict(this.formObj);
        }
        this.$message.success(this.$t("msg.success"));
        this.searchParams.current = 1;
        this.getListHandle(this.searchParams);
        this.isShowEdit = false;
      } catch (error) {
        console.error("添加字典失败:", error);
      }
    },

    async deleteDictHandle(val) {
      try {
        const result = await this.$textShow({
          title: this.$t("tip.label"),
          content: [this.$t("tip.delete")],
        });
        if (!result) return;
        const res = await removeDict(val.id);
        if (res.data.code !== 200) return;
        this.$message.success(this.$t("msg.success"));
        if (
          this.currentHandle === "dictRowDelete" ||
          this.currentHandle === "dictDelete"
        ) {
          this.$refs.dictTable.clearSelect();
          this.loadDictChildList();
        } else {
          this.$refs.table.clearSelect();
          this.searchParams.current = 1;
          this.getListHandle(this.searchParams);
        }
        this.selectList = [];
      } catch (error) {
        console.error("删除字典失败:", error);
      }
    },

    searchDictHandle() {
      this.loadDictChildList();
    },
    resetDictParamsHandle() {
      this.dictSearchParams = {};
      this.loadDictChildList();
    },
  },
};
</script>
